//
//  发送图片.m
//  xinhua_sx
//
//  Created by love on 14-8-13.
//  Copyright (c) 2014年 dangyangyang. All rights reserved.
//
#define kIOS_VERSION [[UIDevice currentDevice].systemVersion floatValue]
#import "发送图片.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MKReverseGeocoder.h>
#import <MapKit/MKPlacemark.h>
#import "AFNetworking.h"
#import "MBProgressHUD.h"

@interface sendimageVieControll()<CLLocationManagerDelegate,UIAlertViewDelegate>
{
    MBProgressHUD* HUD;
}
@property (nonatomic, strong) UITextView* te;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) UILabel* l2;
@property (nonatomic, strong) NSString* dizhistring;
@end

@implementation sendimageVieControll
@synthesize iamge = _iamge;
@synthesize te = _te;
@synthesize l2 = _l2;
@synthesize locationManager =_locationManager;
@synthesize dizhistring = _dizhistring;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGFloat aY = kIOS_VERSION<7.0?0:20;
    UIView* _navBar = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 44.0+aY)];
    _navBar.backgroundColor = [UIColor colorWithRed:2.0/255 green:102.0/255 blue:172.0/255 alpha:1.0];
    _navBar.userInteractionEnabled = YES;
    
    UILabel* _titleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, aY, self.view.frame.size.width, 44)];
    _titleLable.backgroundColor = [UIColor clearColor];
    _titleLable.textColor = [UIColor whiteColor];
    _titleLable.font = [UIFont systemFontOfSize:20];
    _titleLable.textAlignment = NSTextAlignmentCenter;
    _titleLable.text = @"图片上传";
    [_navBar addSubview:_titleLable];
    [self.view addSubview:_navBar];
    UIButton* _leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, aY, 40,40.0)];
    [_leftButton setImage:[UIImage imageNamed:@"icon_back@2x.png"] forState:UIControlStateNormal];
    
    _leftButton.imageEdgeInsets = UIEdgeInsetsMake(10, 13, 5, 5);
    [_leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_leftButton];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, aY+50, 80, 80)];
    imageView.contentMode = UIViewContentModeScaleToFill;
    imageView.image = _iamge;
    [self.view addSubview:imageView];
    UITextView* text1 = [[UITextView alloc] initWithFrame:CGRectMake(100, aY+50, 200, 80)];
    text1.text = @"图片描述";
    //text1.borderStyle =
    text1.layer.borderColor = [UIColor grayColor].CGColor;
    text1.layer.borderWidth = 1.0;
    [self.view addSubview:text1];
    self.te = text1;
    UILabel* l1 = [[UILabel alloc] initWithFrame:CGRectMake(10, aY+150, 100, 20)];
    l1.text =@"我的位置";
    
    [self.view addSubview:l1];
    UILabel* l2 = [[UILabel alloc] initWithFrame:CGRectMake(100, aY+140, 220, 40)];
    l2.font = [UIFont systemFontOfSize:12];
    l2.numberOfLines = 2;
    l2.backgroundColor = [UIColor clearColor];
    [self.view addSubview:l2];
    self.l2 = l2;
    l2.text = @"正在定位";
    _dizhistring  =@"山西";
    [self loadLI];
    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(20, 280, 280,30)];
    [button setTitle:@"提交" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(fabu) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundColor:[sendimageVieControll colorWithHexString:@"#A6C4E8"]];
    [self.view addSubview:button];
    
    
    // Do any additional setup after loading the view.
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_te resignFirstResponder];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100086)
    {
        [self back];
    }
}
-(void)loadLI
{
    // 判断定位操作是否被允许
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        
        self.locationManager.delegate = self;
    }else {
        //提示用户无法进行定位操作
    }
    
    // 开始定位
    [_locationManager startUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    [self.locationManager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    
    CLLocationCoordinate2D coor = currentLocation.coordinate;
   
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];NSLog(@"222");
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error) {
        if (array.count > 0) {
            
            CLPlacemark *placemark = [array objectAtIndex:0];
           
            
            NSString *country = placemark.ISOcountryCode;
            NSString *city = placemark.locality;
            NSLog(@"name:%@\n country:%@\n postalCode:%@\n ISOcountryCode:%@\n ocean:%@\n inlandWater:%@\n locality:%@\n subLocality:%@\n administrativeArea:%@\n subAdministrativeArea:%@\n thoroughfare:%@\n subThoroughfare:%@\n",
                                                placemark.name,
                                                placemark.country,
                                                placemark.postalCode,
                                                placemark.ISOcountryCode,
                                                placemark.ocean,
                                                placemark.inlandWater,
                                                placemark.administrativeArea,
                                                placemark.subAdministrativeArea,
                                                placemark.locality,
                                               placemark.subLocality,
                                placemark.thoroughfare,
                                            placemark.subThoroughfare);
            NSLog(@"Country = %@", placemark.country);
                         NSLog(@"Postal Code = %@", placemark.postalCode);
                         NSLog(@"Locality = %@", placemark.locality);
                         NSLog(@"address = %@",placemark.name);
                        NSLog(@"administrativeArea = %@",placemark.administrativeArea);
                        NSLog(@"subAdministrativeArea = %@",placemark.subAdministrativeArea);
                        NSLog(@"locality = %@", placemark.locality);
                         NSLog(@"thoroughfare = %@", placemark.thoroughfare);
            
            NSLog(@"---%@..........%@. %@.cout:%d",country,city,placemark.name,[array count]);
            self.l2.text = placemark.name;
            _dizhistring = [NSString stringWithFormat:@"%@",placemark.subAdministrativeArea];
        }
    }];

    
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
	
    if (error.code == kCLErrorDenied) {
        NSLog(@"error =%@",error);
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
    }
}
-(void)fabu
{
    NSString* string = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/photosHand.html"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSString* uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"UID"];
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = @"正在上传";
    HUD.dimBackground = YES;
    [self.view addSubview:HUD];
    [HUD show:YES];
    if (!uid)
    {
        [HUD hide:YES];
        UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请重新登录!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [v1 show];
        
        return;
        

    }
    NSLog(@"dishi  =%@",_dizhistring);
    NSDictionary* dic = @{@"address":_dizhistring, @"content":_te.text, @"frontUserId":uid, @"code":COUTURYCODE};
    
    ///NSString* sting = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/imageSave.html"];
    [manager  POST:string  parameters:dic  constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
        
        NSData * data =  UIImagePNGRepresentation(self.iamge); //将拍下的图片转化成data
        
        [formData appendPartWithFileData:data name:@"uploadedfile" fileName:@"1" mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject){
        id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        NSLog(@"json = %@",jsonObject);
        [HUD hide:YES];
        NSString* string = [NSString stringWithFormat:@"%@",jsonObject[@"result"]];
        if ([string isEqualToString:@"success"])
        {
            UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"上传成功!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            v1.tag = 100086;
            [v1 show];
       
           // NSUserDefaults* de = [NSUserDefaults standardUserDefaults];
           // [de removeObjectForKey:@"UID"];
           // [de synchronize];
            
            NSLog(@"1222");
          //  [[NSNotificationCenter defaultCenter] postNotificationName:@"Logout1" object:nil];
            NSLog(@"2233");
        }
        //self.usreL.text = [jsonObject objectForKey:@"name"];
        //self.nameL.text = [jsonObject objectForKey:@"nickName"];
        //[self.ve setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://183.203.18.45:7001%@",jsonObject[@"qRcodePath"]]] placeholderImage:[UIImage imageNamed:@"base_detail_default_pic.png"]];
    } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
        [HUD hide:YES];
        UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"上传失败!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [v1 show];
        NSLog(@"error = %@",error);
    }];

}
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    self.iamge = nil;
    
    // Dispose of any resources that can be recreated.
}
+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
